package com.of.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.of.mapper.ItemDescMapper;
import com.of.mapper.ItemMapper;
import com.of.pojo.Item;
import com.of.pojo.ItemDesc;
import com.of.vo.ItemVo;
import com.of.vo.PageResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    @Override
    public PageResult getItemList(PageResult pageResult) {
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(flag,"title", pageResult.getQuery());
        //定义分页对象
        IPage<Item> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        //page的参数由原来的页数、条数 经过业务调用添加了 总记录数 和 分页的结果
        page=itemMapper.selectPage(page, queryWrapper);//3+2
        long total = page.getTotal();//获取总数
        List<Item> rows = page.getRecords();//获取分页的结果
        return pageResult.setRows(rows).setTotal(total);
    }
    @Override
    @Transactional
    public void saveItem(ItemVo itemVo){
        //1.实现Item对象入库
        Item item = itemVo.getItem().setStatus(true);
        //刚开始id为null，入库操作时，id在数据库中会自动赋值
        //赋值之后，对象中的ID依然为null
        itemMapper.insert(item);
        //2.实现ItemDesc对象入库
        ItemDesc itemDesc = itemVo.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void updateStatus(Item item) {
       itemMapper.updateById(item);
    }

    @Override
    public void updateItem(Item item) {
        item.setNum(item.getNum())
                .setSellPoint(item.getSellPoint())
                .setPrice(item.getPrice())
                .setTitle(item.getTitle())
                .setUpdated(new Date());
        itemMapper.updateById(item);

    }

    @Override
    public Item findItemById(Integer id) {
        return itemMapper.findItemById(id);
    }
}
